package com.shujia.flink.sink

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.base.DeliveryGuarantee
import org.apache.flink.connector.kafka.sink.{KafkaRecordSerializationSchema, KafkaSink}
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}

object Demo7KafkaSink {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //读取一个文件
    val carsDS: DataStream[String] = env.readTextFile("flink/data/cars.json")


    /**
     * 创建kafka sink
     */
    val kafkaSink: KafkaSink[String] = KafkaSink
      .builder[String]()
      //kafka 集群列表
      .setBootstrapServers("master:9092,node1:9092,node2:9092")
      .setRecordSerializer(KafkaRecordSerializationSchema.builder()
        //指定topic
        .setTopic("cars")
        //指定序列化方式
        .setValueSerializationSchema(new SimpleStringSchema())
        .build()
      )
      //指定数据处理的语义AT_LEAST_ONCE：至少一次,EXACTLY_ONCE:唯一一次
      .setDeliverGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
      .build()

    //使用kafka sink
    carsDS.sinkTo(kafkaSink)

    env.execute()

  }

}
